//
//  ViewController.m
//  AFNetworkingDemo
//
//  Created by UniHan_iMac on 17/4/7.
//  Copyright © 2017年 UniHan_iMac. All rights reserved.
//

#import "ViewController.h"
#import <AFNetworking.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)SDWebImage
{
    // 获取一张图片
    [_imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"] placeholderImage:[UIImage imageNamed:@"duck"]];
    
    // 使用block设置图片
    [_imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"] placeholderImage:[UIImage imageNamed:@"duck.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        _imageView.image = image;
    }];
    
    // 使用SDWebImageManager设置图片
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager downloadImageWithURL:[NSURL URLWithString:@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        NSLog(@"进度%f",1.0 * receivedSize / expectedSize);
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        NSLog(@"下载完成");
        _imageView.image = image;
    }];
    
    // 内存缓存 磁盘缓存
    [_imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"] placeholderImage:[UIImage imageNamed:@"duck.png"] options:SDWebImageCacheMemoryOnly | SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        _imageView.image = image;
        switch (cacheType) {
            case SDImageCacheTypeNone:
                NSLog(@"直接下载");
                break;
            case SDImageCacheTypeDisk:
                NSLog(@"磁盘缓存");
                break;
            case SDImageCacheTypeMemory:
                NSLog(@"内存缓存");
                break;
            default:
                break;
        }
    }];
    
    // 播放GIF动画
    [_imageView sd_setAnimationImagesWithURLs:@[@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491816039517&di=96107314e737a0a820021347dd08dc05&imgtype=0&src=http%3A%2F%2Ff1.diyitui.com%2F37%2F6f%2Fe3%2F9f%2Fed%2F4c%2F73%2Fa1%2F09%2F8b%2F2d%2F04%2F8c%2F1d%2Fef%2Fdd.jpg",@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"]];
    
    // 清除缓存数据
    [[SDWebImageManager sharedManager].imageCache clearDisk];
    [[SDWebImageManager sharedManager].imageCache clearMemory];
    // 取消当前进行的所有下载操作
    [[SDWebImageManager sharedManager] cancelAll];
}

- (void)getOrPostRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 超时时间
    manager.requestSerializer.timeoutInterval = 10;
    // 声明上传的是json格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 声明上传的是普通格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 声明获取到的是json格式
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    // 声明获取到的是普通格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 将请求参数放在请求的字典里
    NSDictionary *parameterDict = @{@"username":@"zhang",@"password":@"123"};
    // 发送get请求
    [manager GET:@"请求的URL" parameters:parameterDict progress:^(NSProgress * _Nonnull downloadProgress) {
        // 获取目前数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功
        if(responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dict);
        } else {
            NSLog(@"暂无数据");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
    }];
    
    // 发送post请求
    [manager POST:@"" parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark 图片下载
- (void)downloadTask
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        // 告诉服务器文件保存的路径
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"%@",filePath);
        
        // 判断目录里面是否存在这个图片
        if([[NSFileManager defaultManager] fileExistsAtPath:[filePath path]] == YES)
        {
            // 更新界面需要使用主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIImage *image = [UIImage imageWithContentsOfFile:[filePath path]];
                _imageView.frame = CGRectMake(0, 20, image.size.width, image.size.height);
                _imageView.image = [UIImage imageWithContentsOfFile:[filePath path]];
            });
        }
    }];
    [downloadTask resume];
}

#pragma mark 图片上传
- (void)uploadTask
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"上传进度:%lf",1.0 * uploadProgress.completedUnitCount  / uploadProgress.totalUnitCount);
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if(error) {
            NSLog(@"上传失败:%@",error);
        } else {
            NSLog(@"上传成功");
        }
    }];
    [uploadTask resume];
}

- (void)download
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:@"http://www.feizl.com/upload2007/2011_05/110505164429412.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // 下载进度
        NSLog(@"当前下载进度为：%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount );
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 下载地址
        NSLog(@"默认下载地址:%@",targetPath);
        // 设置下载路径
        NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSLog(@"设置下载地址:%@",filePath);
        return [NSURL fileURLWithPath:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        // 下载完成调用的方法
    }];
    [downloadTask resume];
}

- (void)upload
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"duck.png"]);
        [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 上传进度
        NSLog(@"上传进度:%lf",1.0 * uploadProgress.completedUnitCount  / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功
        NSLog(@"请求成功:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"请求失败:%@",error);
    }];
}

#pragma mark 网络监听
- (void)AFNetworkStatus{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"当前网络状态:%@",AFStringFromNetworkReachabilityStatus(status));
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络状态");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据网");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"wifi网络");
                break;
            default:
                break;
        }}];
    [manager startMonitoring];
}


@end
